<style></style>

<template>
    <div>
        <el-button type="danger" @click="batchDeleteBtn">批量删除</el-button>
        <el-tree :data="menus" :props="defaultProps" :default-expanded-keys="expandedkey" node-key="catId" show-checkbox
            :expand-on-click-node="false" draggable :allow-drop="allowDrop" :allow-drag="allowDrag" ref="menuTree">
            <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span>
                    <el-button v-if="node.level <= 2" type="text" size="mini" @click="() => append(data)">
                        添加
                    </el-button>
                    <el-button type="text" size="mini" @click="() => edit(data)">
                        编辑
                    </el-button>
                    <el-button v-if="node.childNodes.length == 0" type="text" size="mini"
                        @click="() => remove(node, data)">
                        删除
                    </el-button>
                </span>
            </span>
        </el-tree>
        <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <el-form :model="category">
                <el-form-item label="分类名称">
                    <el-input v-model="category.name" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <el-form :model="category">
                <el-form-item label="图标">
                    <el-input v-model="category.icon" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <el-form :model="category">
                <el-form-item label="计量单位">
                    <el-input v-model="category.productUnit" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitData">确 定</el-button>
            </span>

        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            maxLevel: 0,
            menus: [],
            expandedkey: [],
            defaultProps: {
                children: "children",
                label: "name"
            },
            title: "",
            dialogType: "",
            dialogVisible: false,
            category: {
                catId: null,
                name: "",
                parentCid: 0,
                catLevel: 0,
                showStatus: 1,
                sort: 0,
                icon: "",
                productUnit: ""
            }
        }
    },
    methods: {
        getMenus() {
            this.$http({
                url: this.$http.adornUrl('/product/category/list/tree'),
                method: 'get'
            })
                .then(response => {
                    console.log("成功获得到菜单数据...", response.data.data)
                    this.menus = response.data.data
                }).catch((error) => {
                    console.log(error)
                });
        },

        append(data) {
            console.log("append", data)
            this.dialogVisible = true
            this.dialogType = "add"
            this.title = "添加"
            // 点击的时候进行category对象的赋值
            this.category.parentCid = data.catId
            this.category.catLevel = data.catLevel * 1 + 1
            this.category.catId = null
            this.category.name = ""
            this.category.icon = ""
            this.category.productUnit = ""
            this.category.sort = 0
            this.category.showStatus = 1
        },

        edit(data) {
            console.log("edit", JSON.stringify(data))
            this.dialogVisible = true
            this.dialogType = "edit"
            this.title = "修改"
            // 发送请求获取节点最新的信息
            this.$http({
                url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
                method: 'get'
            })
                .then(response => {
                    // 请求成功
                    // 点击的时候进行category对象的赋值
                    this.category.name = response.data.category.name
                    this.category.catId = response.data.category.catId
                    this.category.icon = response.data.category.icon
                    this.category.productUnit = response.data.category.productUnit
                    this.category.parentCid = response.data.category.parentCid

                    this.category.catLevel = response.data.category.catLevel
                    this.category.showStatus = response.data.category.showStatus
                    this.category.sort = response.data.category.sort
                }).catch((error) => {
                    console.log(error)
                });
        },

        remove(node, data) {
            console.log("remove", node, data)
            var ids = [data.catId]

            this.$confirm(`是否删除【${data.name}】菜单?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http({
                    url: this.$http.adornUrl('/product/category/delete'),
                    method: 'post',
                    data: this.$http.adornData(ids, false)
                })
                    .then(response => {
                        console.log("成功删除菜单数据...", response.data.deleteRow)
                        this.$message({
                            type: 'success',
                            message: '菜单删除成功!'
                        });
                        this.getMenus()
                        // 刷新完页面后重新给默认展开的key赋值
                        this.expandedkey = [node.parent.data.catId]
                        console.log("被激活的key:", this.expandedkey)
                    }).catch((error) => {
                        console.log("请求失败...", error)
                    });
            }).catch(() => {
                // this.$message({
                //     type: 'info',
                //     message: '已取消删除'
                // });
            });
        },

        /**
         * 批量删除
         */
        batchDeleteBtn() {
            let catIds = [];
            let checkedNodes = this.$refs.menuTree.getCheckedNodes();
            console.log("被选中的元素", checkedNodes)
            // 循环遍历获取所有准备删除的id
            for (let i = 0; i < checkedNodes.length; i++) {
                catIds.push(checkedNodes[i].catId);
            }
            // 先弹窗进行确认，确认后再进行删除的逻辑
            this.$confirm(`是否批量删除【${catIds}】菜单?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http({
                    url: this.$http.adornUrl('/product/category/delete'),
                    method: 'post',
                    data: this.$http.adornData(catIds, false)
                })
                    .then(response => {
                        console.log("成功删除菜单数据...", response.data.deleteRow)
                        this.$message({
                            type: 'success',
                            message: '菜单删除成功!'
                        });
                        this.getMenus()
                        // 刷新完页面后重新给默认展开的key赋值
                        // this.expandedkey = [node.parent.data.catId]
                        // console.log("被激活的key:", this.expandedkey)
                    }).catch((error) => {
                        console.log("请求失败...", error)
                    });
            }).catch(() => {
                // this.$message({
                //     type: 'info',
                //     message: '已取消删除'
                // });
            });
        },

        submitData() {
            console.log("提交的数据：", JSON.stringify(this.category))
            if (this.dialogType == "add") {
                // 调用添加的方法
                this.addCategory()
            } else if (this.dialogType == "edit") {
                // 调用修改的方法
                this.updateCategory()
            }
        },

        addCategory() {
            console.log("data:", JSON.stringify(this.category))
            this.$http({
                url: this.$http.adornUrl('/product/category/save'),
                method: 'post',
                data: this.$http.adornData(this.category, false)
            })
                .then(response => {
                    console.log("成功保存菜单数据...", response)
                    this.$message({
                        type: 'success',
                        message: '菜单保存成功!'
                    });
                    // 成功保存后需要关闭页面
                    this.dialogVisible = false
                    // 再次去查询
                    this.getMenus()
                    // 刷新完页面后重新给默认展开的key赋值
                    this.expandedkey = [this.category.parentCid]
                    // 保存完成后同时将对象清空
                    this.category = {}
                }).catch((error) => {
                    console.log("请求失败...", error)
                });
        },

        updateCategory() {
            this.$http({
                url: this.$http.adornUrl('/product/category/update'),
                method: 'post',
                data: this.$http.adornData(this.category, false)
            })
                .then(response => {
                    console.log("成功修改菜单数据...", response)
                    this.$message({
                        type: 'success',
                        message: '菜单修改成功!'
                    });
                    // 成功修改后需要关闭页面
                    this.dialogVisible = false
                    // 再次去查询
                    this.getMenus()
                    // 刷新完页面后重新给默认展开的key赋值
                    this.expandedkey = [this.category.parentCid]
                }).catch((error) => {
                    console.log("请求失败...", error)
                });
        },
        handleClose() {

        },
        allowDrop(draggingNode, dropNode, type) {
            // 判断被拖动的当前节点，以及父节点的总层数相加 不能大于3
            // 计算当前节点的总层数
            this.countNodeLevel(draggingNode.data)
            // 当前正在拖动的节点 + 父节点所在的深度 <= 3
            let deep = this.maxLevel - draggingNode.data.catLevel + 1
            console.log("深度：", deep)
            // 判断当前拖动节点的类型
            if (type == "inner") {
                // 拖动到节点里面
                // return deep + dropNode.level <= 3
                return true
            } else {
                // return deep + dropNode.parent.level <= 3
                return true
            }
        },
        countNodeLevel(node) {
            // 找到所有子节点，求最大深度
            if (node.children != null && node.children.length > 0) {
                for (let i = 0; i < node.children.length; i++) {
                    if (node.children[i].catLevel > this.maxLevel) {
                        this.maxLevel = node.children[i].catLevel
                    }
                    this.countNodeLevel(node.children[i])
                }
            }
        }

    },
    created() {
        this.getMenus()
    }
};
</script>